#include "cg_remote_control/net_endpoint.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>

namespace CG
{
NetEndPoint::NetEndPoint() : NetEndPoint(0) {}

NetEndPoint::NetEndPoint(int port)
{
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
}

NetEndPoint::NetEndPoint(std::string ip, int port)
{
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
}
NetEndPoint::NetEndPoint(sockaddr_in sockaddr)
{
    addr = sockaddr;
}
bool NetEndPoint::operator<(const NetEndPoint &p) const
{
    int ret = p.addr.sin_addr.s_addr - addr.sin_addr.s_addr;
    if (ret == 0)
    {
        return p.addr.sin_port - addr.sin_port > 0;
    }
    return ret > 0;
}

std::string NetEndPoint::IP() const
{
    return inet_ntoa(addr.sin_addr);
}

int NetEndPoint::Port() const
{
    return addr.sin_port;
}

bool NetEndPoint::IsValid() const
{
    return addr.sin_port != 0;
}

bool NetEndPoint::IsAnyAddr() const
{
    return addr.sin_addr.s_addr == htonl(INADDR_ANY);
}
} // namespace CG